﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Menus.Commands.Add;

/// <summary>
/// 校验菜单信息
/// </summary>
public class AddMenuCommandValidator : AbstractValidator<AddMenuCommand>
{
    private readonly IApplicationDbContext _context;
    public AddMenuCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(x => x.ParentId).MustAsync(ValidParentIdAsync).WithMessage("非法移动！");

        RuleFor(x => x.Code)
            .MustAsync(BeUniqueCodeAsync).WithMessage("权限值重复！");
    }

    /// <summary>
    /// 菜单移动是否合法
    /// </summary>
    /// <param name="command"></param>
    /// <param name="parentId"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> ValidParentIdAsync(AddMenuCommand command, long? parentId, CancellationToken cancellationToken)
    {
        if (parentId == null)
            return true;

        return await _context.Menus.AnyAsync(x => x.Id == parentId, cancellationToken);
    }

    /// <summary>
    /// 校验权限值是否唯一
    /// </summary>
    /// <param name="command"></param>
    /// <param name="code"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    private async Task<bool> BeUniqueCodeAsync(AddMenuCommand command, string? code, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            return true;
        }
        var menu = await _context.Menus.FirstOrDefaultAsync(x => x.Code == code, cancellationToken);
        if (menu == null)
        {
            return true;
        }
        return false;
    }
}